from django import template 
 from util import parse_args_kwargs_and_as_var
 from queryutils import executor
 
 register = template.Library()
 
 @register.tag(name="query")
 def do_query(parser, token):
     nodelist = parser.parse(('endquery',))
     args, kwargs, as_var = parse_args_kwargs_and_as_var(parser, token.split_contents()[1:])
     parser.delete_first_token()
     return QueryNode(args, kwargs, as_var, nodelist)
 
 class QueryNode(template.Node):
     def __init__(self, args, kwargs, as_var, nodelist):
         self.as_var = as_var
         self.evalto = kwargs.get('eval_to', None)
         self.onsuccessjsfunc = kwargs.get('success_func', False)
         self.onfailurejsfunc = kwargs.get('failure_func', False)
         self.name = kwargs.get('name')
         self.query = kwargs.get('query').var
         self.queryargs = template.Variable(kwargs.get('query_args', '-1'))
         self.source = kwargs.get('source', 'default')
         
     def render(self, context):
         script = ''
         jscallback = ''
         result = executor.get('default').execute({'query' : self.query, 'query_args': self.queryargs.resolve(context)}).fetchall()
 
         if (self.evalto == None):
             evalto = template.Variable("eval_to").resolve(context)
         else:
             evalto = self.evalto.token
             
         if (self.as_var == None):
             as_var = template.Variable("as").resolve(context)
         else:
             as_var = self.as_var
 
         evalto = str(evalto)
         as_var = str(as_var)
         
         if (evalto == 'context'):
             context[as_var] = result
         elif (evalto == 'js'):
             script = script + 'if(!__query__) __query__={}; __query__["__' + as_var + '__"]' + ' = ' + repr(result) + '; '
             if (self.onsuccessjsfunc):
                 jscallback = self.onsuccessjsfunc.token
                 script = script + jscallback + ('.call(null, %s)' % repr(result)) + '; '
                 script = '''<script type='text/javascript' language='javascript'>%s</script>''' % script
         elif (evalto == 'jsonp'):
             script = script + as_var + ('(%s)' % repr(result)) + '; '
         
         output = ''
         if (len(script) > 0):
             output = script
         return output